import {
  getContacts,
  setChatMessageReads,
  getNoReadMessages,
  addSystemMessage,
  getSystemMessages,
  setSystemMessageRead,
  getNoReadNums,
  getReadMessages
} from './chat.api'
import $vue from '@/main'
export default {
  namespaced: true,
  state: {
    tabs: [
      { icon: 'el-icon-date', badge: 0 },
      { icon: 'el-icon-date', badge: 0 },
      { icon: 'el-icon-date', badge: 0 }
    ],
    curTab: 1,
    contacts: [],
    contact: null,
    messages: []
  },
  mutations: {

  },
  actions: {
    initChat ({state, rootState}) {
      state.contact = null
      getContacts({}).then(res => {
        if (res.status === 200) {
          state.contacts = []
          let params = []
          res.data.map(contact => {
            contact.badge = 0
            state.contacts.push(contact)
            params.push({
              userId: rootState.user.uid,
              friendId: contact.userid
            })
          })
          getNoReadNums(params).then(res => {
            if (res.status === 200) {
              state.tabs[1].badge = 0
              res.data.map((num, index) => {
                state.tabs[1].badge += num
                state.contacts[index].badge = num
              })
            } else {
              $vue.$notify.error({
                title: '提示',
                message: res.msg
              })
            }
          })
        } else {
          $vue.$notify.error({
            title: '提示',
            message: res.msg
          })
        }
      })
    },
    selectContact ({state, rootState}, contact) {
      state.contact = contact
      state.curTab = 0
      state.tabs[1].badge -= state.contact.badge
      getNoReadMessages({
        userId: rootState.user.uid,
        friendId: contact.userid
      }).then(res => {
        if (res.status === 200) {
          setChatMessageReads({
            userId: rootState.user.uid,
            friendId: contact.userid
          }).then(res2 => {
            if (res2.status === 200) {
              state.messages = res.data
            } else {
              $vue.$notify.error({
                title: '提示',
                message: res.msg
              })
            }
          })
        } else {
          $vue.$notify.error({
            title: '提示',
            message: res.msg
          })
        }
      })
    },
    tabClick ({state, dispatch}, index) {
      state.curTab = index
      if (index === 1) {
        dispatch('initChat')
      }
    }
  }
}
